package com.it.base.support.string;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * html标签处理工具类
 */
public class HTMLUtil {

    private static final Pattern IMAGE_TAG_PATTERN = Pattern.compile("<(img|IMG)(.*?)>");
    private static Pattern IMAGE_SRC_PATTERN = Pattern.compile("(src|SRC)=\"(.*?)\"");
    private static Pattern IMAGE__SRC_PATTERN = Pattern.compile("(_src|_SRC)=\"(.*?)\"");


    public static String delHTMLTag(String htmlStr){
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";

        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
        Matcher m_script=p_script.matcher(htmlStr);
        htmlStr=m_script.replaceAll(""); //过滤script标签

        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
        Matcher m_style=p_style.matcher(htmlStr);
        htmlStr=m_style.replaceAll(""); //过滤style标签

        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
        Matcher m_html=p_html.matcher(htmlStr);
        htmlStr=m_html.replaceAll(""); //过滤html标签

        Pattern p_imge=Pattern.compile(regEx_img,Pattern.CASE_INSENSITIVE);
        Matcher m_imge=p_imge.matcher(htmlStr);
        htmlStr=m_imge.replaceAll(""); //过滤image标签

        return htmlStr.trim(); //返回文本字符串
    }

    //处理img标签  获取src路径内容
    public static String matchImgSrcTag(String srcStr) {

        List<String> targets = new ArrayList<>();
        // 针对src标签
        // 先匹配img标签
        Matcher imageTagMatcher = IMAGE_TAG_PATTERN.matcher(srcStr);
        while (imageTagMatcher.find()) {
            String image = imageTagMatcher.group(2).trim();
            // 获取src后面的内容
            Matcher imageSrcMatcher = IMAGE_SRC_PATTERN.matcher(image);
            String src = null;
            if (imageSrcMatcher.find()) {
                src = imageSrcMatcher.group(2).trim();
            }
            if (src == null || src.isEmpty()) {
                continue;
            }
            //System.out.println("src:" + src);
            targets.add(src);
        }

        // 针对_src标签
        while (imageTagMatcher.find()) {
            String image = imageTagMatcher.group(2).trim();
            Matcher imageSrcMatcher = IMAGE__SRC_PATTERN.matcher(image);
            String src = null;
            if (imageSrcMatcher.find()) {
                src = imageSrcMatcher.group(2).trim();
            }
            if (src == null || src.isEmpty()) {
                continue;
            }
            //System.out.println("_src_:" + src);
            targets.add(src);
        }
        return targets.get(0);
    }



}
